import { defineStore } from 'pinia'
import type { SensorData } from '../types/sensor'

interface State {
  connectionStatus: 'connected' | 'disconnected'
  temperature: string | null
  humidity: string | null
  light: string | null
  dataStream: SensorData[]
}

export const useSensorStore = defineStore('sensor', {
  state: (): State => ({
    connectionStatus: 'disconnected',
    temperature: null,
    humidity: null,
    light: null,
    dataStream: []
  }),
  actions: {
    updateData(payload: SensorData) {
      if (payload.temperature) this.temperature = payload.temperature
      if (payload.humidity) this.humidity = payload.humidity
      if (payload.light) this.light = payload.light
      
      this.dataStream.unshift({
        ...payload,
        createTime: new Date().toLocaleTimeString()
      })
      
      if (this.dataStream.length > 10) this.dataStream.pop()
    },
    setConnectionStatus(status: 'connected' | 'disconnected') {
      this.connectionStatus = status
    }
  }
})